package com.tsx.wiki.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tsx.wiki.dto.EbookDTO;
import com.tsx.wiki.dto.EbookPageDTO;
import com.tsx.wiki.mapper.EbookMapper;
import com.tsx.wiki.pojo.Ebook;
import com.tsx.wiki.result.PageResult;
import com.tsx.wiki.service.EbookService;
import com.tsx.wiki.vo.EbookQueryVo;
import com.tsx.wiki.vo.EbookVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class EbookServiceImpl implements EbookService {
    @Resource
    private EbookMapper ebookMapper;

    @Override
    public PageResult<EbookVo> page(EbookPageDTO ebookPageDTO) {
        PageHelper.startPage(ebookPageDTO.getCurrent(), ebookPageDTO.getPageSize());
        Ebook ebook = Ebook.builder()
                .name(ebookPageDTO.getName())
                .category1Id(ebookPageDTO.getCategory1Id())
                .category2Id(ebookPageDTO.getCategory2Id())
                .description(ebookPageDTO.getDescription())
                .build();
        List<EbookVo> list = ebookMapper.selectAllByPageWithCategoryName(ebook);
        log.info("{}", list);
        PageInfo<EbookVo> ebookVoPageInfo = new PageInfo<>(list);
        PageResult<EbookVo> pageResult = new PageResult<>();
        pageResult.setRecords(ebookVoPageInfo.getList());
        pageResult.setTotal(ebookVoPageInfo.getTotal());
        return pageResult;
    }

    @Override
    public List<Ebook> list(EbookDTO ebookDTO) {
        Ebook ebook = toEbook(ebookDTO);
        return ebookMapper.selectAll(ebook);
    }

    @Override
    public EbookQueryVo selectById(Long id) {
        return ebookMapper.selectById(id);
    }

    @Override
    public void update(EbookDTO ebookDTO) {
        Ebook ebook = toEbook(ebookDTO);
        ebookMapper.update(ebook);
    }

    @Override
    public void save(EbookDTO ebookDTO) {
        Ebook ebook = toEbook(ebookDTO);
        ebookMapper.save(ebook);
    }

    @Override
    public void deleteById(Long id) {
        ebookMapper.deleteById(id);
    }

    private Ebook toEbook(EbookDTO ebookDTO) {
        return Ebook.builder()
                .id(ebookDTO.getId())
                .name(ebookDTO.getName())
                .category1Id(ebookDTO.getCategory1Id())
                .category2Id(ebookDTO.getCategory2Id())
                .description(ebookDTO.getDescription())
                .build();
    }
}
